package cn.lovemmd.model.controller;

import cn.lovemmd.model.common.Result;
import cn.lovemmd.model.dto.LoginResult;
import cn.lovemmd.model.service.CodeService;
import cn.lovemmd.model.service.UserService;
import cn.lovemmd.model.util.JwtUtil;
import com.alibaba.fastjson2.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 用户控制器 - 用户展示页面后台
 * 使用FastJson2进行JSON序列化
 * 
 * @author TLS
 * @since 2024-01-01
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "用户管理接口")
public class UserController {
    
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    
    private final UserService userService;
    private final CodeService codeService;
    private final JwtUtil jwtUtil;

    /**
     * 处理用户登录请求
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回登录结果的JSON字符串
     */
    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("用户登录")
    public ResponseEntity<String> login(
            @ApiParam("用户名") @RequestParam("username") String username,
            @ApiParam("密码") @RequestParam("password") String password) {
        
        try {
            // 使用新的登录方法，返回详细结果
            LoginResult loginResult = userService.loginWithResult(username, password);
            
            if (loginResult.isSuccess()) {
                // 登录成功，生成JWT token（24小时有效期）
                String token = jwtUtil.generateUserToken(username);
                
                Map<String, Object> data = new HashMap<>();
                data.put("token", token);
                data.put("username", username);
                data.put("expiresIn", 86400); // 24小时
                
                Result<Map<String, Object>> response = Result.success(data);
                log.info("用户登录成功: {}", username);
                return ResponseEntity.ok(JSON.toJSONString(response));
            } else {
                // 登录失败，返回具体错误信息
                Result<String> response = Result.error(loginResult.getErrorMessage());
                log.warn("用户登录失败: {} - {}", username, loginResult.getErrorMessage());
                return ResponseEntity.ok(JSON.toJSONString(response));
            }
        } catch (Exception e) {
            log.error("登录异常", e);
            Result<String> response = Result.error("登录失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(response));
        }
    }

    /**
     * 处理用户注册请求
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param qq 用户的QQ号
     * @return 返回注册结果的JSON字符串
     */
    @PostMapping(value = "/register", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("用户注册")
    public ResponseEntity<String> register(
            @ApiParam("用户名") @RequestParam("username") String username,
            @ApiParam("密码") @RequestParam("password") String password,
            @ApiParam("验证码") @RequestParam("code") String code,
            @ApiParam("QQ号") @RequestParam("qq") String qq) {
        
        try {
            // 验证授权码
            if (codeService.FindCode(code) == null || Objects.equals(codeService.FindCode(code), "")) {
                Result<String> response = Result.error("授权码无效！");
                return ResponseEntity.ok(JSON.toJSONString(response));
            }
            
            if (codeService.FindCodeStatus(code) == 1) {
                Result<String> response = Result.error("授权码已失效！");
                return ResponseEntity.ok(JSON.toJSONString(response));
            }
            
            // 检查用户名是否已存在
            if (userService.findUser(username) == 1) {
                Result<String> response = Result.error("用户名已存在！");
                return ResponseEntity.ok(JSON.toJSONString(response));
            }
            
            // 执行注册
            if (userService.register(username, password, code, qq) == 1) {
                // 更新授权码状态
                codeService.updateCodeStatus(code);
                
                Result<String> response = Result.success("注册成功");
                log.info("用户注册成功: {}", username);
                return ResponseEntity.ok(JSON.toJSONString(response));
            } else {
                Result<String> response = Result.error("注册失败");
                log.warn("用户注册失败: {}", username);
                return ResponseEntity.ok(JSON.toJSONString(response));
            }
        } catch (Exception e) {
            log.error("注册异常", e);
            Result<String> response = Result.error("注册失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(response));
        }
    }

    /**
     * 处理用户登出请求
     *
     * @param username 用户名
     * @return 返回登出结果的JSON字符串
     */
    @PostMapping(value = "/logout", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation("用户登出")
    public ResponseEntity<String> logout(
            @ApiParam("用户名") @RequestParam("username") String username) {
        
        try {
            // 由于使用JWT，登出只需要客户端删除token即可
            // 这里可以记录登出日志
            log.info("用户登出: {}", username);
            
            Result<String> response = Result.success("登出成功");
            return ResponseEntity.ok(JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("登出异常", e);
            Result<String> response = Result.error("登出失败：" + e.getMessage());
            return ResponseEntity.ok(JSON.toJSONString(response));
        }
    }
}
